package nio.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Author: admin
 * @Description:
 * @Date: 2018/11/12 10:39
 */

public class NioSocketClient {
    public static void main(String[] args) throws InterruptedException {
        try {
            Selector selector = Selector.open();
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
            //socketChannel.socket().connect(new InetSocketAddress("127.0.0.1",9999));
            socketChannel.register(selector, SelectionKey.OP_READ);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put("hello server".getBytes());
            if (socketChannel.finishConnect()) {
                buffer.flip();

                while (buffer.hasRemaining()) {
                    socketChannel.write(buffer);
                }
                while (true) {
                    selector.select();
                    Thread.sleep(10000);
                    Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
                    while (selectionKeys.hasNext()) {
                        SelectionKey key = selectionKeys.next();
                        if (key.isReadable()) {
                            SocketChannel sc = (SocketChannel) key.channel();
                            int readLen = 0;
                            buffer.clear();
                            StringBuilder sb = new StringBuilder();
                            while ((readLen = sc.read(buffer)) > 0) {
                                // 切换到读模式
                                buffer.flip();
                                byte[] temp = new byte[readLen];
                                buffer.get(temp, 0, readLen);
                                buffer.clear();
                                sb.append(new String(temp));
                            }
                            System.out.println("接收消息：" + sb.toString());
                            buffer.clear();
                            buffer.put("exit".getBytes());
                            buffer.flip();
                            while (buffer.hasRemaining()){
                                socketChannel.write(buffer);
                            }
                            return;
                        }
                        selectionKeys.remove();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
